<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="staffSearch" class="demo-form-inline">
        <!--条件查询-->
        <el-form-item>
          <el-input v-model="staffSearch.sname" placeholder="员工姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="staffSearch.addr" placeholder="住址"></el-input>
        </el-form-item>
        <el-form-item> 
          <el-select v-model="staffSearch.scid" placeholder="所在学校">
            <el-option label="所有学校" value="0"></el-option>
            <el-option :label="c.scname" :value="c.scid" v-for="c in departmentList" :key="c.scid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addstaff">添加教师</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="staffList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="工号"
            align="center"
            prop="sid"
            width="180"/>
        <el-table-column
            label="姓名"
            prop="sname"
            align="center"/>
        <el-table-column
            label="性别"
            prop="sex"
            align="center"/>
        <el-table-column
            label="年龄"
            prop="sage"
            align="center"/>
        <el-table-column
            label="住址"
            prop="addr"
            align="center"/>
        <el-table-column
            label="所在部门"
            prop="scname"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页导航面板-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <!--编辑【添加/修改】员工对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="staff" :rules="rules" ref="ruleForm">
        <el-form-item label="员工姓名" prop="sname" :label-width="formLabelWidth">
          <el-input v-model="staff.sname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工性别" prop="sex" :label-width="formLabelWidth">
          <el-radio v-model="staff.sex" label="男">男</el-radio>
          <el-radio v-model="staff.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="员工年龄" prop="sage" :label-width="formLabelWidth">
          <el-input v-model.number="staff.sage" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="家庭住址" prop="addr" :label-width="formLabelWidth">
          <el-input v-model="staff.addr" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="所在部门" prop="scid" :label-width="formLabelWidth">
          <el-select v-model="staff.scid" placeholder="请选择所在部门">
            <el-option label="所有部门" value="0"></el-option>
            <el-option :label="d.scname" :value="d.scid" v-for="d in departmentList" :key="d.scid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="savestaff">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import staffApi from "@/api/teacher"
import departmentApi from "@/api/school"

export default {
  data() {
    // 校验员工年龄的规则
    let checkAge = (rule, value, callback) => {
      if (value === '' || value == null) {    //js中会自动将0转换为null
        return callback(new Error('年龄不能为空！'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('年龄必须为整数！'))
      } else if (value < 1 || value > 150) {
        return callback(new Error('年龄必须在1~150之间！'))
      } else {
        callback()
      }
    }


    return {     
      staffList: [],
      page: 1,        
      pageSize: 5,    
      total: 20,     
      staffSearch: {}, 
      departmentList: [],   
      dialogFormVisible: false,  
      staff: {},       
      title: '添加员工信息',  
      formLabelWidth: '100px', 
      multipleSelection:[],     
      sids: [],                 
      // 定义添加的校验规则
      rules: {
        // 1. 校验姓名
        sname: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
        ],
        // 2. 校验性别
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'},
        ],
        // 3. 校验年龄
        sage: [
          // 定义一个方法验证年龄
          { validator : checkAge, trigger: 'blur'}
        ],
        // 4. 校验住址
        addr: [
          {required: true, message: '请输入住址', trigger: 'blur'},
        ],
        // 5. 校验
        scid: [
          {required: true, message: '请选择部门', trigger: 'blur'},
        ]
      }
    }
  }
  ,
  created() {
    this.search()
    this.findAlldepartment()
  },
  methods: {
    // 1. 查询所有员工
    async findstaffs() {
      const {data: res} = await staffApi.findAllStaffs()
      console.log(res)
      if (data.code === 200) {
        this.staffList = res.data.list
      }
    },
    // 2. 分页查询
    async findByPage() {
      const {data: res} = await staffApi.findByPage(this.page, this.pageSize)
      console.log(res)
      if (res.code === 200) {
        this.staffList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    // 3. 查询所有部门
    async findAlldepartment() {
      const {data: res} = await departmentApi.findAllDepartment()
      console.log(res)
      if (res.code === 200) {
        this.departmentList = res.data.list
      }
    },
    // 4. 条件查询带分页
    async search() {
      const {data: res} = await staffApi.search(this.page, this.pageSize, this.staffSearch)
      console.log(res)
      if (res.code === 200) {
        this.staffList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    // 5. 添加员工
    addstaff() {
      // 5.1 修改对话框标题
      this.title = "添加员工信息"
      // 5.2 清空原来的数据
      this.staff = {}
      // 5.3 打开对话框
      this.dialogFormVisible = true
    },
    // 6. 保存员工
    // 在添加员工时要注意没有sid字段,可以修改数据库的sid字段为自增字段
     savestaff() {
      this.$refs.ruleForm.validate(async valid => {
        // 6.1 根据是否有sid这个主键值判断是添加还是修改 存在sid是修改员工,否则是添加员工
        let url = "/tearcher/add"      // 默认地址是添加员工
        let method = "post"           // 添加是post请求
        if(this.staff.sid){
          url = "/teacher/update"    // 如果有值就改为修改员工
          method = "put"             // 修改是put请求
        }
        // 6.2 向后端发送请求,执行添加或修改员工
        if (valid) {
         const {data:res} = await staffApi.save(url,method,this.staff)
          //console.log("res:",res)
          if (res.code === 200) {     // 后端执行成功返回200
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {        // 关闭对话框时的回调
                // 6.3 关闭对话框
                this.dialogFormVisible = false
                // 6.4 重新查询
                this.search()
              }
            })
          }else{                      // 后端执行失败返回500
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },
    // 当pagesize大小发生改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      // this.findByPage()
      this.search()
      console.log(`每页 ${val} 条`);
    },
    // 当页码page发生改变时触发
    handleCurrentChange(val) {
      this.page = val
      // this.findByPage()
      this.search()
      console.log(`当前页: ${val}`);
    },
    // 编辑员工
    handleEdit(index, row) {
      // 1. 修改对话框标题
      this.title = '修改员工信息'
      // 2. 显示要修改的员工信息到对话框
      this.staff = row
      // 3. 打开对话框
      this.dialogFormVisible = true

      //console.log(index, row);
    },
    //删除员工信息
    handleDelete(index, row) {
      this.sids = []

      // 判断是否是批量删除，且没有选择任何员工
      if (!row && this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请先选择要删除的员工'
        })
        return;  // 如果没有选择员工，直接返回，不进行删除操作
      }

      if (row) {  // 代表删除单个员工
        this.sids.push(row.sid)
      } else {  // 批量删除
        this.sids = this.multipleSelection.map(m => m.sid)
      }

      this.$confirm(`是否真的要删除学号为${this.sids}的员工吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {  // 点击了"确定"按钮后执行
        let _this = this
        staffApi.deletestaff(this.sids)
          .then(({ data: res }) => {
            console.log("res:", res)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.message,
                onClose: () => {
                  // 重新加载数据
                  _this.search()
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
      }).catch(() => {  // 点击了"取消"按钮后执行
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style>

#app {
  display: flex;
  justify-content: center;
}

.el-card {
  width: 90%;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
